class UUIDGenerator {
    // 生成UUID v4（随机UUID）
    static generateV4() {
        try {
            // 现代浏览器支持crypto.randomUUID()
            if (crypto && crypto.randomUUID) {
                return { success: true, data: crypto.randomUUID() };
            }
            
            // 回退到手动实现
            const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
                const r = Math.random() * 16 | 0;
                const v = c === 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });
            
            return { success: true, data: uuid };
        } catch (error) {
            return { success: false, error: `生成UUID失败: ${error.message}` };
        }
    }

    // 生成UUID v1（基于时间戳）
    static generateV1() {
        try {
            // UUID v1 需要节点ID和时钟序列，这里使用简化版本
            const now = Date.now();
            const timeHigh = ((now / 1000) * 10000000 + 0x01b21dd213814000) & 0xffffffff;
            const timeMid = (timeHigh >>> 32) & 0xffff;
            const timeHiAndVersion = ((timeHigh >>> 16) & 0x0fff) | 0x1000;
            const clockSeq = Math.floor(Math.random() * 0x3fff) | 0x8000;
            
            // 生成随机节点ID（48位）
            const node = [];
            for (let i = 0; i < 6; i++) {
                node.push(Math.floor(Math.random() * 256));
            }
            
            const uuid = [
                (timeHigh & 0xffffffff).toString(16).padStart(8, '0'),
                timeMid.toString(16).padStart(4, '0'),
                timeHiAndVersion.toString(16).padStart(4, '0'),
                clockSeq.toString(16).padStart(4, '0'),
                node.map(b => b.toString(16).padStart(2, '0')).join('')
            ].join('-');
            
            return { success: true, data: uuid };
        } catch (error) {
            return { success: false, error: `生成UUID v1失败: ${error.message}` };
        }
    }

    // 生成Nil UUID（全零UUID）
    static generateNil() {
        return { success: true, data: '00000000-0000-0000-0000-000000000000' };
    }

    // 批量生成UUID
    static generateBatch(count, version = 'v4', options = {}) {
        try {
            if (!count || count <= 0) {
                return { success: false, error: '生成数量必须大于0' };
            }

            if (count > 10000) {
                return { success: false, error: '批量生成数量不能超过10000个' };
            }

            const {
                format = 'default',
                separator = '\n',
                prefix = '',
                suffix = '',
                uppercase = false,
                removeDashes = false
            } = options;

            const uuids = [];
            
            for (let i = 0; i < count; i++) {
                let result;
                switch (version) {
                    case 'v1':
                        result = this.generateV1();
                        break;
                    case 'nil':
                        result = this.generateNil();
                        break;
                    case 'v4':
                    default:
                        result = this.generateV4();
                        break;
                }
                
                if (!result.success) {
                    return result;
                }
                
                let uuid = result.data;
                
                // 处理格式选项
                if (removeDashes) {
                    uuid = uuid.replace(/-/g, '');
                }
                
                if (uppercase) {
                    uuid = uuid.toUpperCase();
                }
                
                // 添加前缀和后缀
                uuid = prefix + uuid + suffix;
                
                uuids.push(uuid);
            }

            const output = uuids.join(separator);
            
            return { 
                success: true, 
                data: {
                    uuids,
                    output,
                    count: uuids.length
                }
            };

        } catch (error) {
            return { success: false, error: `批量生成UUID失败: ${error.message}` };
        }
    }

    // 验证UUID格式
    static validate(uuid) {
        try {
            if (!uuid || typeof uuid !== 'string') {
                return { 
                    success: true, 
                    data: { 
                        valid: false, 
                        error: 'UUID不能为空或必须是字符串' 
                    } 
                };
            }

            const uuidTrimmed = uuid.trim();
            
            // UUID v4 正则表达式
            const uuidV4Regex = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
            // UUID v1 正则表达式
            const uuidV1Regex = /^[0-9a-f]{8}-[0-9a-f]{4}-1[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
            // 通用UUID格式
            const uuidGeneralRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
            // 无破折号UUID格式
            const uuidNoDashRegex = /^[0-9a-f]{32}$/i;

            let version = null;
            let format = 'standard';
            let valid = false;

            if (uuidV4Regex.test(uuidTrimmed)) {
                valid = true;
                version = 'v4';
            } else if (uuidV1Regex.test(uuidTrimmed)) {
                valid = true;
                version = 'v1';
            } else if (uuidGeneralRegex.test(uuidTrimmed)) {
                valid = true;
                version = 'unknown';
            } else if (uuidNoDashRegex.test(uuidTrimmed)) {
                valid = true;
                format = 'no-dash';
                // 从无破折号格式中推断版本
                const withDashes = uuidTrimmed.replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, '$1-$2-$3-$4-$5');
                if (uuidV4Regex.test(withDashes)) {
                    version = 'v4';
                } else if (uuidV1Regex.test(withDashes)) {
                    version = 'v1';
                } else {
                    version = 'unknown';
                }
            } else if (uuidTrimmed === '00000000-0000-0000-0000-000000000000') {
                valid = true;
                version = 'nil';
            }

            return { 
                success: true, 
                data: { 
                    valid,
                    version,
                    format,
                    standardForm: valid && format === 'no-dash' ? 
                        uuidTrimmed.replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, '$1-$2-$3-$4-$5') : 
                        uuidTrimmed,
                    error: valid ? null : '不是有效的UUID格式'
                } 
            };

        } catch (error) {
            return { success: false, error: `验证UUID时出错: ${error.message}` };
        }
    }

    // 转换UUID格式
    static convertFormat(uuid, targetFormat = 'standard') {
        try {
            const validateResult = this.validate(uuid);
            if (!validateResult.success) {
                return validateResult;
            }

            if (!validateResult.data.valid) {
                return { success: false, error: validateResult.data.error };
            }

            const cleanUuid = uuid.trim().replace(/-/g, '').toLowerCase();
            
            switch (targetFormat) {
                case 'uppercase':
                    return { 
                        success: true, 
                        data: cleanUuid.replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, '$1-$2-$3-$4-$5').toUpperCase()
                    };
                
                case 'lowercase':
                    return { 
                        success: true, 
                        data: cleanUuid.replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, '$1-$2-$3-$4-$5')
                    };
                
                case 'no-dash':
                    return { 
                        success: true, 
                        data: cleanUuid
                    };
                
                case 'no-dash-uppercase':
                    return { 
                        success: true, 
                        data: cleanUuid.toUpperCase()
                    };
                
                case 'braces':
                    return { 
                        success: true, 
                        data: `{${cleanUuid.replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, '$1-$2-$3-$4-$5')}}`
                    };
                
                case 'standard':
                default:
                    return { 
                        success: true, 
                        data: cleanUuid.replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, '$1-$2-$3-$4-$5')
                    };
            }

        } catch (error) {
            return { success: false, error: `转换UUID格式失败: ${error.message}` };
        }
    }

    // 解析UUID信息
    static parse(uuid) {
        try {
            const validateResult = this.validate(uuid);
            if (!validateResult.success) {
                return validateResult;
            }

            if (!validateResult.data.valid) {
                return { success: false, error: validateResult.data.error };
            }

            const standardUuid = validateResult.data.standardForm.toLowerCase();
            const parts = standardUuid.split('-');
            
            const info = {
                uuid: standardUuid,
                version: validateResult.data.version,
                format: validateResult.data.format,
                parts: {
                    timeLow: parts[0],
                    timeMid: parts[1],
                    timeHiAndVersion: parts[2],
                    clockSeqHiAndReserved: parts[3].substring(0, 2),
                    clockSeqLow: parts[3].substring(2),
                    node: parts[4]
                }
            };

            // 如果是v1 UUID，尝试解析时间信息
            if (validateResult.data.version === 'v1') {
                try {
                    const timeHi = parseInt(parts[2], 16) & 0x0fff;
                    const timeMid = parseInt(parts[1], 16);
                    const timeLow = parseInt(parts[0], 16);
                    const timestamp = (timeHi * Math.pow(2, 48)) + (timeMid * Math.pow(2, 32)) + timeLow;
                    const unixTime = (timestamp - 0x01b21dd213814000) / 10000;
                    
                    info.timestamp = {
                        raw: timestamp,
                        unix: Math.floor(unixTime),
                        date: new Date(Math.floor(unixTime)).toISOString()
                    };
                } catch (e) {
                    info.timestamp = { error: '无法解析时间戳' };
                }
            }

            return { success: true, data: info };

        } catch (error) {
            return { success: false, error: `解析UUID失败: ${error.message}` };
        }
    }
}